package com.ityuhao.tech.concurrency.atomic;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Semaphore;

@Slf4j
@Service
public class AtomicDemo3 {

    @Autowired
    private StringRedisTemplate redisTemplate;

    // 请求总数
    public static int clientTotal = 5000;

    // 同时并发执行的线程数
    public static int threadTotal = 200;

    public void demo() throws Exception {
        init();
        ExecutorService executorService = Executors.newCachedThreadPool();
        final Semaphore semaphore = new Semaphore(threadTotal);
        final CountDownLatch countDownLatch = new CountDownLatch(clientTotal);
        for (int i = 0; i < clientTotal; i++) {
            executorService.execute(() -> {
                try {
                    semaphore.acquire();
                    add();
                    semaphore.release();
                } catch (Exception e) {
                    log.error("exception", e);
                }
                countDownLatch.countDown();
            });
        }
        countDownLatch.await();
        executorService.shutdown();
        log.info("count:{}", redisTemplate.opsForValue().get(redisKey));
    }

    private void add() {
        redisTemplate.opsForValue().increment(redisKey);
    }

    private String redisKey = "count";

//    private void add() {
//        Long count = Long.valueOf(redisTemplate.opsForValue().get(redisKey));
//        count++;
//        log.info(String.valueOf(count));
//        redisTemplate.opsForValue().set(redisKey, String.valueOf(count));
//    }

    private void init() {
        redisTemplate.opsForValue().set(redisKey, "1");
    }
}
